// 管理员状态管理
import { defineStore } from 'pinia'
import apiClient from '../api'

export const useAdminStore = defineStore('admin', {
    state: () => ({
        users: {
            data: [],
            loading: false,
            error: null
        },
        pendingCompanies: {
            data: [],
            loading: false,
            error: null
        },
        applications: {
            data: [],
            loading: false,
            error: null
        },
        materials: {
            data: [],
            loading: false,
            error: null
        },
        statistics: {
            data: null,
            loading: false,
            error: null
        },
        positions: {
            data: [],
            loading: false,
            error: null
        },

        internships: {
            data: [],
            loading: false,
            error: null
        }
    }),

    actions: {
        // 获取用户列表
        async fetchUsers(params = {}) {
            try {
                const response = await apiClient.get('/admin/users', { params })
                this.users = response.data
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取用户列表失败')
            }
        },
        // 创建用户
        async createUser(userData) {
            try {
                const response = await apiClient.post('/admin/users', userData)
                if (this.users.data) {
                    this.users.data.unshift(response.data)
                }
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '创建用户失败')
            }
        },
        // 获取用户详情
        async getUserDetail(userId) {
            try {
                const response = await apiClient.get(`/admin/users/${userId}/detail`)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取用户详情失败')
            }
        },
        // 更新用户
        async updateUser(userId, userData) {
            try {
                const response = await apiClient.put(`/admin/users/${userId}`, userData)
                // 不需要手动更新本地数据，通过重新获取列表来更新
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '更新用户失败')
            }
        },
        // 重置用户密码
        async resetUserPassword(userId, data) {
            try {
                const response = await apiClient.put(`/admin/users/${userId}/reset-password`, data)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '重置密码失败')
            }
        },
        // 删除用户
        async deleteUser(userId) {
            try {
                await apiClient.delete(`/admin/users/${userId}`)
                this.users = this.users.filter(user => user.id !== userId)
                return true
            } catch (error) {
                throw new Error(error.response?.data?.message || '删除用户失败')
            }
        },
        // 切换用户状态
        async toggleUserStatus(userId) {
            try {
                console.log('发送切换用户状态请求:', {
                    url: `/admin/users/${userId}/toggle-status`,
                    method: 'PUT'
                });

                const response = await apiClient.put(`/admin/users/${userId}/toggle-status`)
                console.log('切换用户状态响应:', response);

                // 正确访问store中的users状态
                const userData = this.users.data || [];
                const user = userData.find(user => user.id === userId)
                if (user) {
                    // toggle操作：切换状态
                    user.status = user.status === 1 ? 0 : 1
                }
                return response.data
            } catch (error) {
                console.error('切换用户状态API错误:', error);
                throw new Error(error.response?.data?.message || error.message || '切换用户状态失败')
            }
        },

        // 获取待审核企业
        async fetchPendingCompanies() {
            try {
                const response = await apiClient.get('/admin/companies/pending')
                this.pendingCompanies = response.data
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取待审核企业失败')
            }
        },
        // 获取企业列表（新增）
        async fetchCompanies(params = {}) {
            try {
                const response = await apiClient.get('/admin/companies', { params })
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取企业列表失败')
            }
        },

        // 获取企业详情（新增）
        async getCompanyDetails(companyId) {
            try {
                const response = await apiClient.get(`/admin/companies/${companyId}`)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取企业详情失败')
            }
        },

        // 审核企业（修改现有方法以适应新的API路径）
        async reviewCompany(companyId, data) {
            try {
                const response = await apiClient.put(`/admin/companies/${companyId}/review`, data)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '审核企业失败')
            }
        },

        // 获取所有申请
        async fetchAllApplications() {
            try {
                const response = await apiClient.get('/admin/applications')
                this.applications = response.data
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取申请列表失败')
            }
        },

        // 处理申请
        async processApplication(applicationId, data) {
            try {
                const response = await apiClient.put(`/admin/applications/${applicationId}/process`, data)
                const index = this.applications.findIndex(app => app.id === applicationId)
                if (index !== -1) {
                    this.applications[index] = response.data
                }
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '处理申请失败')
            }
        },

        // 获取所有材料
        async fetchAllMaterials() {
            try {
                const response = await apiClient.get('/admin/materials')
                this.materials = response.data
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取材料列表失败')
            }
        },

        // 审核材料
        async reviewMaterial(materialId, data) {
            try {
                const response = await apiClient.put(`/admin/materials/${materialId}/review`, data)
                const index = this.materials.findIndex(material => material.id === materialId)
                if (index !== -1) {
                    this.materials[index] = response.data
                }
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '审核材料失败')
            }
        },

        // 获取统计数据
        async fetchStatistics() {
            try {
                const response = await apiClient.get('/admin/statistics/internship')
                this.statistics = response.data
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取统计数据失败')
            }
        },
        async getSystemStatistics() {
            try {
                const response = await apiClient.get('/admin/statistics/system')
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取系统统计数据失败')
            }
        },
        // 获取实习岗位列表
        async fetchInternshipPositions(params = {}) {
            try {
                const response = await apiClient.get('/internship-positions', { params })
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取实习岗位列表失败')
            }
        },

        // 获取实习列表
        async fetchInternships(params = {}) {
            try {
                const response = await apiClient.get('/internships', { params })
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取实习列表失败')
            }
        },
        // 添加以下新方法
        async updateStudent(userId, studentData) {
            try {
                const response = await apiClient.put(`/admin/students/${userId}`, studentData)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '更新学生信息失败')
            }
        },

        async updateTeacher(userId, teacherData) {
            try {
                const response = await apiClient.put(`/admin/teachers/${userId}`, teacherData)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '更新教师信息失败')
            }
        },

        async updateCompany(userId, companyData) {
            try {
                const response = await apiClient.put(`/admin/companies/${userId}`, companyData)
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '更新企业信息失败')
            }
        },

        // 获取教师列表
        async fetchTeachers() {
            try {
                const response = await apiClient.get('/admin/teachers');
                return response.data;
            } catch (error) {
                throw new Error(error.response?.data?.message || '获取教师列表失败');
            }
        },

        async togglePositionStatus(positionId) {
            try {
                const response = await apiClient.put(`/internship-positions/${positionId}/admin-toggle-status`)
                // 更新本地数据
                const position = this.positions.data?.find(p => p.id === positionId)
                if (position) {
                    position.status = response.data.status
                }
                return response.data
            } catch (error) {
                throw new Error(error.response?.data?.message || '切换岗位状态失败')
            }
        }


    }
})
